import './index.less';
import React, { useState, useEffect } from 'react';
import {
  Table,
  Input,
  Button,
  message,
  Modal,
  Divider,
  Card,
  Form,
} from 'antd';
import {
  getUserList,
  userDelete,
  userListAdd,
  userListUpdate,
} from './service';
import columnsData from './data';

const index = () => {
  // 根据条件查询的列表数据
  const [datas, setDatas] = useState([]);
  // 删除提示框显示状态
  const [isModalVisible, setIsModalVisible] = useState(false);
  // 删除提示框显示状态
  const [id, setId] = useState('');
  // 查询条件姓名
  const [name, setName] = useState('');
  // 用户添加模态框显示状态
  const [addModal, setAddModal] = useState(false);
  // 用户编辑模态框显示状态
  const [editModal, setEditModal] = useState(false);
  // 添加用户数据表单验证
  const addFormRef: any = React.createRef();
  // 用户数据修改表单交互
  const [editForm] = Form.useForm();

  // table表格组合操作
  const columns = columnsData;
  // 定义操作行
  const columnsRender: any = {
    action: (text: any, record: any, index: number) => (
      <div>
        <a onClick={() => editUser(record)}>修改</a>
        <Divider type="vertical" />
        <a onClick={() => handleRemove(record.id)}>删除</a>
      </div>
    ),
  };
  // 表格头部数据
  columns.forEach((item: any) => {
    if (
      (item.dataIndex === 'userType' || item.dataIndex === 'action') &&
      !item.render
    ) {
      item.render = columnsRender[item.dataIndex];
    }
  });

  // 数据加载
  useEffect(() => {
    getDatas({ name });
  }, []);

  /**
   * 数据查询
   * @param params 查询的参数对象
   */
  const getDatas = (params: object) => {
    getUserList(params).then(async (res: any) => {
      console.log(res);
      await setDatas(res.body.data);
    });
  };

  // 重置
  const reset = () => {
    setName('');
    getDatas({});
  };

  /**
   * 显示模态框提示是否删除
   * @param id 用户id
   */
  const handleRemove = (id: string) => {
    setId(id);
    setIsModalVisible(true);
  };

  // 确定删除用户数据
  const handleOk = () => {
    userDelete({ id }).then((res: any) => {
      if (res.sysHead.retCd === '000000') {
        getDatas({ name });
        setIsModalVisible(false);
        message.success(res.sysHead.retInf);
      }
    });
  };

  // 添加
  const addModalOk = async () => {
    try {
      // 非空验证
      const validate = await addFormRef.current.validateFields();
      const param = await addFormRef.current.getFieldsValue();

      userListAdd(param).then((res: any) => {
        if (res.sysHead.retCd === '000000') {
          getDatas({ name });
          setAddModal(false);
          message.success(res.sysHead.retInf);
          // 重置表单
          addFormRef.current.resetFields();
        }
      });
    } catch (err) {
      console.log(err);
    }
  };

  /**
   * 编辑-点击打开模态框-回显
   * @param item 行对象数据
   */
  const editUser = async (item: any) => {
    setEditModal(true);
    editForm.setFieldsValue(item);
  };

  // 保存编辑值-修改
  // const editUserOK = () => {
  //   const param = editForm.getFieldsValue();

  //   userListUpdate(param).then((res: any) => {
  //     if (res.sysHead.retCd === '000000') {
  //       getDatas({ name });
  //       setEditModal(false);
  //       message.success(res.sysHead.retInf);
  //     }
  //   });
  // };

  return (
    <div className="bg-gray">
      <div className="flex p-3 mb-2 bg-white">

        {/* 查询表单 */}
        <Form layout="inline">
          <Form.Item label="name:">
            <Input
              onChange={(event: any) => {
                setName(event.target.value);
              }}
              style={{ width: 200 }}
              value={name}
            />
          </Form.Item>

          <Button
            style={{ marginRight: 8 }}
            onClick={() => {
              getDatas({ name });
            }}
            type="primary"
          >
            查询
          </Button>
          <Button onClick={reset}>重置</Button>
        </Form>
      </div>

      {/* 列表展示用户信息 */}
      <Card
        title="用户信息"
        extra={
          <Button
            type="primary"
            onClick={() => {
              setAddModal(true);
            }}
          >
            {' '}
            +添加
          </Button>
        }
        bordered={false}
      >
        <Table
          columns={columns}
          dataSource={datas}
          rowKey={(datas: { id: string }) => datas.id}
        />
      </Card>

      {/* 删除弹框 */}
      <Modal
        cancelText="取消"
        okText="确认"
        title="提示"
        visible={isModalVisible}
        onOk={handleOk}
        onCancel={() => {
          setIsModalVisible(false);
        }}
      >
        是否确定删除本条数据？
      </Modal>

      {/* 新增用户弹窗 */}
      <Modal
        destroyOnClose
        cancelText="取消"
        okText="新增"
        title="用户新增"
        visible={addModal}
        onOk={addModalOk}
        onCancel={() => {
          setAddModal(false);
        }}
      >
        <Form ref={addFormRef}>
          <Form.Item label="姓名" name="name" rules={[{ required: true }]}>
            <Input />
          </Form.Item>
          <Form.Item label="性别" name="sex" rules={[{ required: true }]}>
            <Input />
          </Form.Item>
          <Form.Item label="年龄" name="age" rules={[{ required: true }]}>
            <Input />
          </Form.Item>
          <Form.Item label="地址" name="address" rules={[{ required: true }]}>
            <Input />
          </Form.Item>
        </Form>
      </Modal>

      {/* 修改用户信息弹窗 */}
      <Modal
        destroyOnClose
        cancelText="取消"
        okText="修改"
        title="用户编辑"
        visible={editModal}
        // onOk={editUserOK}
        onCancel={() => {
          setEditModal(false);
        }}
      >
        <Form form={editForm}>
          <Form.Item
            className="d-none"
            label="id"
            name="id"
            rules={[{ required: true }]}
          >
            <Input />
          </Form.Item>
          <Form.Item label="姓名" name="name" rules={[{ required: true }]}>
            <Input />
          </Form.Item>
          <Form.Item label="性别" name="sex" rules={[{ required: true }]}>
            <Input />
          </Form.Item>
          <Form.Item label="年龄" name="age" rules={[{ required: true }]}>
            <Input />
          </Form.Item>
          <Form.Item label="地址" name="address" rules={[{ required: true }]}>
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};
export default index;
